/**
 * ajax表单提交
 */
$(".dataForm").submit(function (e) {
        e.preventDefault();
        var loadT = layer.msg('正在提交，请稍候…', {icon: 16, time: 0, shade: [0.3, "#000"]});
        var form_action = $(this).attr('action');
        var form_method = $(this).attr('method');
        var form_data = new FormData($(this)[0]);
        console.log(form_data)
        console.log('%cajax submit start!', ';color:#333333');
        console.log('action:' + form_action);
        console.log('method:' + form_method);
        console.log('data:' + form_data);
        $.ajax({
                url: form_action,
                dataType: 'json',
                type: form_method,
                data: form_data,
                contentType: false,
                processData: false,
                success: function (result) {
                    //layer.close(loadT);
                    layer.msg(result.msg,{
                        icon: result.code ? 1 : 2
                    });
                    console.log('submit success!');
                    if (result.code === 1) {
                        location.href =  res.url;
                    } else {
                        console.log('%cresult fail', ';color:#f39c12');
                    }

                },
                error: function (xhr, type, errorThrown) {
                    //异常处理；
                    console.log('%csubmit fail!', ';color:#dd4b39');
                    console.log();
                    console.log("type:" + type + ",readyState:" + xhr.readyState + ",status:" + xhr.status);
                    console.log("url:" + form_action);
                    console.log("data:" + form_data);
                    layer.close(loadT);
                    layer.msg('访问错误,代码'+xhr.status,{icon:2});
                }
            }
        );
        return false;
    }
);

/*改变每页显示数量*/
function changePageRows(obj) {
    console.log(getCookie("backend_list_rows"));
    setCookie("backend_list_rows",obj.value,1000);
    window.location.reload();
}

/*设置cookie*/
function setCookie(key,value,t)
{
    var oDate=new Date();
    oDate.setDate(oDate.getDate()+t);
    document.cookie=key+"="+value+"; expires="+oDate.toDateString()+"; path=/";
}

/*获取cookie*/
function getCookie(key){
    var arr1=document.cookie.split("; ");
    for(var i=0;i<arr1.length;i++){
        var arr2=arr1[i].split("=");
        if(arr2[0]==key){
            return decodeURI(arr2[1]);
        }
    }
}


//封装一个移除cookie的函数
function removeCookie(key){
    setCookie(key,"",-1);//把cookie设置为过期

}

/*!* 清除查询表单*/
function clear_form(){
    var url_all =  window.location.href;
    var arr = url_all.split('?');
    var url = arr[0];
    location.replace(url);
}

/*列表中单个选择和取消*/
function check_this(obj) {
    var id = $(obj).attr('value');
    if ($(obj).is(':checked')) {
        if ($.inArray(id, dataDelIds) < 0) {
            dataDelIds.push(id);
        }
    } else {
        if ($.inArray(id, dataDelIds) > -1) {
            dataDelIds.splice($.inArray(id, dataDelIds), 1);
        }
    }

    var all_length = $("input[name='data-checkbox']").length;
    var checked_length = $("input[name='data-checkbox']:checked").length;
    if(all_length==checked_length){
        $("#data-checkall").prop("checked",true);
    }else{
        $("#data-checkall").prop("checked",false);
    }
}

/*全部选择/取消*/
function check_all(obj) {
    dataDelIds = [];
    var all_check = $("input[name='data-checkbox']");
    if ($(obj).is(':checked')) {
        all_check.prop("checked",true);
        $(all_check).each(function () {
            dataDelIds.push(this.value);
        });
    }else{
        all_check.prop("checked",false);
    }
    console.log(dataDelIds);
}

// 返回
$('.form-history-back').on('click', function (event) {
    event.preventDefault();
    history.back(1);
});

//上传图片组件显示预览
$(".form-input-image").change(function () {
    var $file = $(this);
    var fileObj = $file[0];
    var windowURL = window.URL || window.webkitURL;
    var dataURL;
    var $img_id = $(this).data('preview');
    var $img = $("#"+$img_id);
    var fileName =getFileName($file.val());
    var $show_name = $(this).data('showname');
    $("#"+$show_name).html(fileName);
    if (fileObj && fileObj.files && fileObj.files[0]) {
        dataURL = windowURL.createObjectURL(fileObj.files[0]);
        $img.attr('src', dataURL);
    }else{
        console.log('上传图片不显示吗？');
    }
});

//获取文件名
function getFileName(o){
    var pos=o.lastIndexOf("\\");
    return o.substring(pos+1);
}

/** 导出excel **/
function exportData(url) {
    var exportUrl = url||'index.html';
    var openUrl = exportUrl+'?export_data=1&'+$("#commentForm").serialize();
    window.open(openUrl);
}

$(".AjaxButton").on('click', function(){
    var layerConfirm = $(this).data("confirm") || 1;
    console.log(layerConfirm);
    var layerType = $(this).data("type") || 1;
    var layerMethod = $(this).data("method") || 'post';
    var go = $(this).data("go") || 'url://reload';

    var layerWith =$(this).data("width") || '80%';
    var layerHeight =$(this).data("height") || '60%';

    var layerTitle = $(this).data('title');

    var url = $(this).data("url");

    var dataId = $(this).data("id");

    if(dataId===undefined){
        var dataData = $(this).data("data") || {};
    }else{
        if(dataId==='checked'){
            dataId = dataDelIds;
        }
        dataData = {"id":dataId};
    }

    if(typeof(dataData) != 'object') {
        dataData = JSON.parse(dataData);
    }

    /*需要确认操作*/
    if(layerConfirm==1){
        var confirmTitle = $(this).data("confirmTitle") || '操作确认';
        var confirmContent = $(this).data("confirmContent") || '您确定要执行此操作吗?';
        layer.confirm(confirmContent,{title:confirmTitle,closeBtn:1,icon:3},function(){
            if(layerType==1){
                ajaxRequest(url,layerMethod,dataData,go);
            }else if(layerType==2) {
                if(checkAuth(url)){
                    layer.open({
                        type: 2,
                        area: [layerWith, layerHeight],
                        title: layerTitle,
                        closeBtn: 1,
                        shift: 0,
                        content: url+"?request_type=layerconfirm&"+parseParam(dataData)
                    });
                }
            }
        });
    }else{
        if(layerType==1){
            ajaxRequest(url,layerMethod,dataData,go);
        }else if(layerType==2) {
            if(checkAuth(url)){
                layer.open({
                    type: 2,
                    area: [layerWith, layerHeight],
                    title: layerTitle,
                    closeBtn: 1,
                    shift: 0,
                    content: url+"?request_type=layerconfirm&"+parseParam(dataData)
                });
            }
        }
    }
});

function ajaxRequest(url,method,data,go) {
    var loadT = layer.msg('正在请求,请稍候…',{icon:16,time:0,shade: [0.3, '#000']});
    $.ajax({
            url: url,
            dataType: 'json',
            type: method,
            data: data,
            success: function (result) {
                layer.close(loadT);
                layer.msg(result.msg,{
                    icon: result.code ? 1 : 2
                });
                console.log('request success!');
                if (result.code === 1) {
                    console.log('%cresult success', ';color:#00a65a');
                } else {
                    go = 'url://current';
                    console.log('%cresult fail', ';color:#f39c12');
                }
                goUrl(go);
            },
            error: function (xhr, type, errorThrown) {
                //异常处理；
                console.log('%crequest fail!', ';color:#dd4b39');
                console.log();
                console.log("type:" + type + ",readyState:" + xhr.readyState + ",status:" + xhr.status);
                console.log("url:" + url);
                console.log("data:");
                console.log(data);
                layer.close(loadT);
                layer.msg('访问错误,代码'+xhr.status,{icon:2});
            }
        }
    );
}

function goUrl(url) {
    console.log(url);
    if (url=== 'url://current' || url===1) {
        console.log('Stay current page.');
    }else if (url=== 'url://reload'|| url===2) {
        console.log('Reload current page.');
        window.location.reload();
    }else if(url=== 'url://back'|| url===3) {
        console.log('Return to the last page.');
        window.history.back();
    }else {
        console.log('Go to '+url);
        window.location.href=url;
    }
}


/**
 * 检查授权
 */
function checkAuth(url) {
    var hasAuth = false;
    var loadT = layer.msg('正在请求,请稍候…',{icon:16,time:0,shade: [0.3, '#000']});
    $.post({
        url: url,
        data: {"layer_check_auth":1},
        dataType: 'json',
        async:false,
        success: function (result) {
            layer.close(loadT);
            if (result.code === 1) {
                hasAuth = true;
            } else {
                layer.msg(result.msg,{
                    icon:  2
                });
            }
        },
        error: function (xhr, type, errorThrown) {
            layer.msg('访问错误,代码'+xhr.status,{icon:2});
        }
    });
    return hasAuth;
}

function parseParam(param, key) {
    var paramStr = "";
    if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        paramStr += "&" + key + "=" + encodeURIComponent(param);
    } else {
        $.each(param, function (i) {
            var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            paramStr += '&' + parseParam(this, k);
        });
    }
    return paramStr.substr(1);
};